<template>
  <Layout style="height: 100%" class="main">
    <Layout>
      <Header class="header-con clearfix">
        <a class="logo-con fl">
          <img :src="logo" key="max-logo" @click="handleCollapsedChange(!collapsed)" />
          <div class="domaintitle" @click="handleCollapsedChange(!collapsed)">蚓智气量分析系统(SGA)</div>
        </a>
        <header-bar class="fr" :collapsed="collapsed" @on-coll-change="handleCollapsedChange">
          <user :message-unread-count="unreadCount" :user-avatar="userAvatar" :user-name="userName" />
          <fullscreen v-model="isFullscreen" style="margin-right: 10px;" />
          <!-- <div @click="changeTheme" class="theme">主题</div> -->
        </header-bar>
      </Header>

      <Content class="main-content-con">
        <Sider hide-trigger collapsible :width="200" :collapsed-width="54" v-model="collapsed" class="left-sider">
          <side-menu accordion ref="sideMenu" :collapsed="collapsed" @on-select="turnToPage" :menu-list="menuList">
          </side-menu>
        </Sider>
        <Layout class="main-layout-con" :style="{ marginLeft: collapsed ? '54px' : '200px' }">
          <div class="tag-nav-wrapper">
            <span class="tag-nav-text">{{ tagNavList[0].meta.title }}</span>
            <!-- <tags-nav :value="$route" @input="handleClick" :list="tagNavList" @on-close="handleCloseTag" /> -->
          </div>
          <Content class="content-layout-wrap">
            <keep-alive :include="cacheList">
              <router-view />
            </keep-alive>
            <ABackTop :height="100" :bottom="80" :right="50" container=".content-layout-wrap"></ABackTop>
          </Content>
        </Layout>
      </Content>
    </Layout>
  </Layout>
</template>
<script>
import SideMenu from './components/side-menu'
import HeaderBar from './components/header-bar'
import TagsNav from './components/tags-nav'
import User from './components/user'
import ABackTop from './components/a-back-top'
import Fullscreen from './components/fullscreen'
import Language from './components/language'
import ErrorStore from './components/error-store'
import { mapMutations, mapActions, mapGetters } from 'vuex'
import { getNewTagList, routeEqual, getRouteByName } from '@/libs/util'
import routers from '@/router/routers'
import { getMenuTree } from '@/api/routers'
import './main.less'
import Main from '@/components/main'
import menuList from '@/config/menuList'

import { DOMAIN_NANE } from '@/libs/auth.js'
// import { getDeployByDomainId } from '@/api/domain'
import common from '@/mixins/common'
export default {
  mixins: [common],
  name: 'Main',
  components: {
    SideMenu,
    HeaderBar,
    Language,
    TagsNav,
    Fullscreen,
    ErrorStore,
    User,
    ABackTop
  },
  data() {
    return {
      menuType: '1',
      collapsed: false,
      logo: require('@/assets/logo.png'),
      isFullscreen: false,
      theme: true
    }
  },
  created() {
    // this.menuType = getUrlKey('menuType') ? getUrlKey('menuType') : '1';
    // getDeployByDomainId({
    //   domainId: '1'
    // }).then(res => {
    //   if (res.code === '0' && res.data !== null && res.data !== '') {
    //     this.minLogo = res.data.logo ? this.$options.filters.checkImgPrefix(res.data.logo) : require('@/assets/images/titleImg.png');
    //   }
    // });
  },
  computed: {
    ...mapGetters(['errorCount', 'domainList']),
    tagNavList() {
      return this.$store.state.app.tagNavList
    },
    callPageList() {
      return this.$store.state.app.callPageList
    },
    tagRouter() {
      return this.$store.state.app.tagRouter
    },
    userAvatar() {
      return this.$store.state.user.avatarImgPath
    },
    userName() {
      return this.$store.state.user.userName
    },
    cacheList() {
      const list = [
        ...(this.callPageList.length
          ? this.callPageList.filter(item => !(item.meta && item.meta.notCache)).map(item => item.name)
          : [])
      ]
      return list
    },
    menuList() {
      return this.modifyMenuData(menuList)
    },
    local() {
      return this.$store.state.app.local
    },
    hasReadErrorPage() {
      return this.$store.state.app.hasReadErrorPage
    },
    unreadCount() {
      return this.$store.state.user.unreadCount
    },
    // domainList() {
    //   return this.$store.state.user.domainList;
    // },
    domainId: {
      get() {
        return this.$store.state.user.domainId
      },
      set(value) {
        // eslint-disable-next-line no-undef
        this.$store.commit('setDomainId', domainId)
      }
    }
  },
  methods: {
    changeTheme() {
      // do nothing
    },
    modifyMenuData(data = []) {
      let arr = []
      data.forEach(item => {
        if (!item.resChildren) {
          arr.push({
            id: item.id,
            path: item.url,
            meta: {
              title: item.name,
              icon: item.resIcon || 'md-menu'
            },
            component: Main
          })
        } else {
          let fpath
          if (item.url) {
            fpath = item.url
            arr.push({
              path: fpath,
              name: item.name,
              id: item.id,
              meta: {
                title: item.name,
                icon: item.resIcon || 'md-menu'
              },
              component: Main,
              children: [
                {
                  path: fpath,
                  name: item.name,
                  meta: {
                    title: item.name,
                    icon: item.resIcon || 'md-menu'
                  },
                  component: () => import(item.url)
                }
              ]
            })
          } else if (!item.url) {
            let spath
            item.resChildren &&
              item.resChildren.forEach(val => {
                if (val.url) {
                  spath = val.url
                  let spathIndex = spath.lastIndexOf('/')
                  spath = spath.substring(spathIndex, spath.length)
                }
              })
            arr.push({
              path: spath,
              name: item.name,
              id: item.id,
              meta: {
                title: item.name,
                icon: item.resIcon || 'md-menu'
              },
              component: Main
            })
          }
          item.resChildren &&
            item.resChildren.forEach(val => {
              let cpath
              if (val.url) {
                cpath = val.url
                // let cpathIndex = cpath.lastIndexOf('/');
                // cpath = cpath.substring(cpathIndex, cpath.length);
              }
              arr.forEach(arritem => {
                if (val.pid === arritem.id) {
                  if (!arritem.children) {
                    arritem.children = []
                  }
                  arritem.children.push({
                    path: cpath,
                    name: val.name,
                    id: val.id,
                    meta: {
                      title: val.name,
                      icon: val.resIcon || 'md-menu'
                    },
                    component: () => import(val.url)
                  })
                }
              })
            })
        }
      })
      return arr
    },
    // 获取menu tree
    fnGetMenuTree() {
      getMenuTree().then(res => {
        // console.log('menu tree', arr);
      })
    },
    ...mapMutations(['setBreadCrumb', 'setTagNavList', 'addTag', 'setLocal', 'setHomeRoute', 'closeTag']),
    ...mapActions(['handleLogin', 'getUnreadMessageCount', 'getdomainList', 'changeDomainId']),
    turnToPage(route) {
      let { name, params, query } = {}
      if (typeof route === 'string') {
        name = route
        if (name.indexOf('isTurnByHref_') > -1) {
          window.open(name.split('_')[1])
          return
        }
        const arr = getRouteByName(this.menuList, name)
        if (arr.length > 0) {
          return this.$router.push({
            path: arr[0].path,
            query: {
              resId: arr[0].id
            }
          })
        }
      } else {
        name = route.name
        params = route.params
        query = route.query
      }
      this.$router.push({
        name,
        params,
        query
      })
    },
    handleCollapsedChange(state) {
      this.collapsed = state
    },
    handleCloseTag(res, type, route) {
      // console.log(res, route);
      if (type !== 'others') {
        if (type === 'all') {
          this.turnToPage(this.$config.homeName)
        } else {
          if (routeEqual(this.$route, route)) {
            this.closeTag(route)
          }
        }
      }
      this.setTagNavList(res)
    },
    handleClick(item) {
      this.turnToPage(item)
    },
    selectDomain(value) {
      localStorage.setItem(DOMAIN_NANE, JSON.stringify(value))
      this.changeDomainId(value).then(res => {
        window.location.replace('/home')
        // window.location.reload();
      })
    }
  },
  watch: {
    $route(newRoute) {
      const { name, query, params, meta } = newRoute
      this.addTag({
        route: { name, query, params, meta },
        type: 'push'
      })
      this.setBreadCrumb(newRoute)
      this.setTagNavList(getNewTagList(this.tagNavList, newRoute))
      this.$refs.sideMenu.updateOpenName(newRoute.name)
    }
  },
  mounted() {
    /**
     * @description 初始化设置面包屑导航和标签导航
     */
    this.setTagNavList()
    // this.getdomainList().then(res => {
    //   // console.log(res);
    //   this.domainList = res;
    // });
    this.setHomeRoute(routers)
    const { name, params, query, meta } = this.$route
    this.addTag({
      route: { name, params, query, meta }
    })
    this.setBreadCrumb(this.$route)
    // 设置初始语言
    // console.log(this.$i18n.locale);
    this.setLocal(this.$i18n.locale)
    // 如果当前打开页面不在标签栏中，跳到homeName页
    if (!this.tagNavList.find(item => item.name === this.$route.name)) {
      this.$router.push({
        name: this.$config.homeName
      })
    }
    // 获取未读消息条数
    this.getUnreadMessageCount()
  }
}
</script>
<style lang="less" scoped>
@import './main.less';
</style>
